/*
 * @lc app=leetcode.cn id=35 lang=cpp
 *
 * [35] 搜索插入位置
 */

// @lc code=start
class Solution
{
public:
    int searchInsert(vector<int> &nums, int target)
    {
        //二分查找
        int left = 0;
        int right = nums.size() - 1;
        if (nums[0] > target)
        {
            return 0;
        }
        else if (nums[right] < target)
        {
            return right + 1;
        }
        while (left < right)
        {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target)
            {
                left = mid + 1;
            }
            else if (nums[mid] > target)
            {
                right = mid - 1;
            }
            else
            {
                return mid;
            }
        }
        //如果没有找到 返回顺序插入的位置
        return target>nums[right] ? right+1 : right;
    }
};
// @lc code=end
